package com.zyn.rsgl.service.Impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zyn.rsgl.mapper.ScheduleDetailMapper;
import com.zyn.rsgl.mapper.SignMapper;
import com.zyn.rsgl.pojo.Meeting;
import com.zyn.rsgl.pojo.Sign;
import com.zyn.rsgl.pojo.SignStatistics;
import com.zyn.rsgl.service.SignService;
import com.zyn.rsgl.utils.commonResult.R;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 打卡表 服务实现类
 * </p>
 *
 * @author zcs
 * @since 2025-02-24
 */
@Service
public class SignServiceImpl extends ServiceImpl<SignMapper, Sign> implements SignService {

    @Override
    public R listPage(Integer pageNum, Integer pageSize, String userId, LocalDateTime date ,String punchType ,String origin) {
        // 构造查询器
        QueryWrapper<Sign> signQueryWrapper = new QueryWrapper<>();

        if (userId != null && !userId.isEmpty()) {
            signQueryWrapper.eq("user_id", userId);
        }
        if (date != null) {
            // 将 LocalDateTime 转换为 LocalDate
            LocalDate startDate = date.toLocalDate();
            signQueryWrapper.ge("date", startDate.atStartOfDay()); // 大于等于当天的开始时间
            signQueryWrapper.le("date", startDate.atTime(23, 59, 59)); // 小于等于当天的结束时间
        }
        if (punchType != null && !punchType.isEmpty()) {
            signQueryWrapper.eq("punch_type", punchType);
        }
        if (origin != null && !origin.isEmpty()) {
            signQueryWrapper.eq("origin", origin);
        }
        signQueryWrapper.orderBy(true,false,"date");

        Page<Object> page = PageHelper.startPage(pageNum, pageSize);

        // 执行查询
        List<Sign> list = this.list(signQueryWrapper);
        if (list != null) {
            return R.ok(list, page.getTotal());
        }
        return R.fail("查询失败");
    }

    public boolean exists(String userId, LocalDateTime date, String punchType) {
        QueryWrapper<Sign> queryWrapper = new QueryWrapper<>();
        LocalDateTime startOfDay = date.toLocalDate().atStartOfDay();
        LocalDateTime endOfDay = startOfDay.plusDays(1).minusSeconds(1);
        queryWrapper.eq("user_id", userId)
                .eq("punch_type", punchType)
                .ge("date", startOfDay) // 签到时间大于等于当天开始时间
                .le("date", endOfDay);  // 签到时间小于等于当天结束时间
        return this.getOne(queryWrapper) != null;
    }

    @Override
    public R getMonthlyStatistics() {
        List<SignStatistics> statistics = this.baseMapper.getMonthlyStatistics();
        if (statistics != null) {
            return R.ok(statistics);
        }
        return R.fail("统计失败");
    }
}
